package tables;

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Date;
import java.util.Properties;

import beans.Message;

public class JdbcMessage {

	public static void insere(Message m) throws SQLException,
			ClassNotFoundException, IOException {
		// charger le driver
		Properties props = new Properties();
		FileInputStream fis = new FileInputStream(
				"/home/auberi/Documents/JEE/workspace_jee/Alibi/src/connInfoLocal.txt");
		props.load(fis);

		String passwd = props.getProperty("passwd");
		String url = props.getProperty("url");
		String user = props.getProperty("user");
		// charger le driver
		Class.forName("org.postgresql.Driver");
		// se connecter a la base de donnees
		Connection conn = DriverManager.getConnection(url, user, passwd);
		// issue a query (create a statement and execute a query on it)
		Statement state = (Statement) conn.createStatement();

		if (!(m.getDestinataire() instanceof String)
				|| !(m.getExpediteur() instanceof String)
				|| !(m.getDate() instanceof Date)
				|| !(m.getMessage() instanceof String)) {
			System.err.println("Vos arguments n'ont pas le bon type.");
		} else {
			// inserer

			String query = "INSERT INTO message VALUES ('"
					+ m.getDestinataire() + "', '" + m.getExpediteur() + "', '"
					+ JdbcCommentaire.convertDate(m.getDate()) + "', '" + m.getMessage() + "')";

			state.executeUpdate(query);
			state.close();

		}
	}
}